<template>
  <div class="container">
    <div class="search-container">
      <div class="search-option-row"> 
        <label class="search-option-label">申请人</label>
        <div class="search-option-col">
          <el-select
              v-model="listQuery.create_id"
              filterable
              clearable
              placeholder="请选择">
            <el-option
              v-for="item in allUserOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
        <label class="search-option-label">候选人</label>
        <div class="search-option-col">
        <el-input v-model="listQuery.candidate_name" class="select-item" placeholder="请输入" style="width: 180px;" ></el-input> 
        </div>
         <label class="search-option-label">客户公司</label>
        <div class="search-option-col">
        <el-input v-model="listQuery.company_name" class="select-item" placeholder="请输入" style="width: 180px;" ></el-input>
        </div>
        <label class="search-option-label">发票状态</label>
        <div class="search-option-col">
          <el-select class="filter-item" clearable v-model="listQuery.invoice_status" placeholder="请选择" style="width:180px">
            <el-option v-for="item in invoice_status_options" :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="search-button-row" >
        <label class="search-button-label"></label>
        <div class="search-button-col">
        <el-button size="mini" type="primary" icon="el-icon-search" @click="handleFilter" round>搜索</el-button>
        <el-button size="mini" type="primary" icon="el-icon-refresh" @click="clearOptions" round>清空</el-button>
        </div>
      </div>  
    </div>

    <div class="table-container">
      <el-table v-loading="listLoading" border ref="multipleTable" :data="list" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column  fixed="left" type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand" label-width="180px">
              <el-form-item label="客户公司全称:">
                <span v-if="props.row.company"> {{ props.row.company.company_full_name }}</span>
                <span v-else></span>
              </el-form-item>
              <el-form-item label="客户公司税号:">
                <span v-if="props.row.company"> {{ props.row.company.tax_num }}</span>
                <span v-else></span>
              </el-form-item>
              <el-form-item label="客户公司地址电话:">
                <span v-if="props.row.company"> {{ props.row.company.address }} {{ props.row.company.telephone }}
                </span>
                <span v-else></span>
              </el-form-item>
              <el-form-item label="客户公司开户行、账号:">
                <span v-if="props.row.company"> {{ props.row.company.bank_addr }} {{ props.row.company.a_c_no }}</span>
                <span v-else></span>
              </el-form-item>
              <el-form-item label="发票抬头:">
                <span v-if="props.row.company"> {{ props.row.company.invoice_title }}</span>
                <span v-else></span>
              </el-form-item>
              <el-form-item label="客户人事:">
                <span v-if="props.row.hr" >{{ props.row.hr }}</span>
                <span v-else></span>
              </el-form-item>
              <el-form-item label="客户人事邮箱:">
                <span v-if="props.row.hr_email" >{{ props.row.hr_email }}</span>
                <span v-else></span>
              </el-form-item>
              <el-form-item label="邮寄地址及联系方式:">
                <span v-if="props.row.ems_addr"> {{ props.row.ems_addr }}</span>
                <span v-else></span>
                <span v-if="props.row.ems_contact_info"> {{ props.row.ems_contact_info }}</span>
                <span v-else></span>
              </el-form-item>
               <el-form-item label="开票时间:">
                <span v-if="props.row.bill_date"> {{ props.row.bill_date | timeFilter('{y}-{m}-{d}') }}</span>
                <span v-else></span>
              </el-form-item>
              <el-form-item label="快递厂家及单号:">
                <span v-if="props.row.ems_no"> {{ props.row.ems_no }}</span>
                <span v-else></span>
              </el-form-item>

              <el-form-item label="当前处理人:">
                <span v-if="props.row.current_op_name" >{{ props.row.current_op_name }}</span>
                <span v-else></span>
              </el-form-item>

              <el-form-item label="退款金额:">
                <span v-if="props.row.refund_amount" >{{ props.row.refund_amount }}</span>
                <span v-else>0</span>
              </el-form-item>

              <el-form-item label="备注:">
                <span v-if="props.row.remark"> {{ props.row.remark }}</span>
                <span v-else></span>
              </el-form-item>

              <el-form-item label="发票附件" >
                <span v-if="props.row.invoice_attachment_url">
                  <img :src="props.row.invoice_attachment_url" height="300px" width="600px">
                </span>
                <span v-else>暂无</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column fixed="left" label="客户公司" min-width="200">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.invoice_type | invoiceTypeFilter }}</el-tag>
            <el-tag>{{ scope.row.fee_type | feeTypeFilter }}</el-tag>
            <div v-if="scope.row.company" >{{ scope.row.company.company_name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="项目" width="120px">
          <template slot-scope="scope">
            {{ scope.row.project_name }}
          </template>
        </el-table-column>
        <el-table-column label="客户经理" width="80px">
          <template slot-scope="scope">
            {{ getUsernameById(scope.row.client_manager) }}
          </template>
        </el-table-column>
        <el-table-column  label="候选人" width="120px">
          <template slot-scope="scope">
            {{ scope.row.candidate_name }}
          </template>
        </el-table-column>
        <el-table-column label="内容" width="80px">
          <template slot-scope="scope">{{ scope.row.content}}</template>
        </el-table-column>
        <el-table-column label="金额" width="80px">
          <template slot-scope="scope">{{ scope.row.invoice_amount}}</template>
        </el-table-column>
        <el-table-column label="状态" width="110px">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.status | invoiceStatusFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="申请人" width="90px" >
          <template slot-scope="scope">{{ scope.row.create_name }}</template>
        </el-table-column>
        <el-table-column label="申请时间" width="160px">
          <template slot-scope="scope">{{ scope.row.create_date | timeFilter('{y}-{m}-{d} {h}:{i}:{s}') }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="60px">
          <template slot-scope="scope">
            <el-dropdown @command="handleCommand" trigger="click">
                <span class="el-dropdown-link">
                  <svg-icon icon-class="code" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="checkOperable(scope.row.status, 'apply' ) && selfOperable(scope.row)" :command='{type:"apply", data: scope.row}' >提交申请</el-dropdown-item>
                  <el-dropdown-item v-if="checkOperable(scope.row.status, 'back') && selfOperable(scope.row)" :command='{type:"back", data: scope.row}' >撤回申请</el-dropdown-item>
                  <el-dropdown-item v-if="checkOperable(scope.row.status, 'check') && (clientManagerOperable(scope.row) || hasRoles(['SUPER_ADMIN']))" :command='{type:"check", data: scope.row}' >审核</el-dropdown-item>
                  <el-dropdown-item v-if="checkOperable(scope.row.status, 'print') && (clientManagerOperable(scope.row) || hasRoles(['INVOICE_INFO_BILL', 'SUPER_ADMIN']))" :command='{type:"print", data: scope.row}' >打印</el-dropdown-item>
                  <el-dropdown-item v-if="checkOperable(scope.row.status, 'repulse') && hasRoles(['INVOICE_INFO_BILL', 'SUPER_ADMIN'])" :command='{type:"repulse", data: scope.row}' >打回</el-dropdown-item>
                  <el-dropdown-item v-if="checkOperable(scope.row.status, 'bill') && hasRoles(['INVOICE_INFO_BILL', 'SUPER_ADMIN'])" :command='{type:"bill", data: scope.row}' >开票</el-dropdown-item>
                  <el-dropdown-item v-if="checkOperable(scope.row.status, 'alloc') && hasRoles(['INVOICE_INFO_BILL', 'SUPER_ADMIN'])" :command='{type:"alloc", data: scope.row}' >回款</el-dropdown-item>
                  <el-dropdown-item v-if="checkOperable(scope.row.status, 'refund') && hasRoles(['INVOICE_INFO_BILL', 'SUPER_ADMIN'])" :command='{type:"refund", data: scope.row}' >退款</el-dropdown-item>
                  <el-dropdown-item v-if="checkOperable(scope.row.status, 'cancel') && hasRoles(['INVOICE_INFO_BILL', 'SUPER_ADMIN'])" :command='{type:"cancel", data: scope.row}' divided>作废</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
      <el-pagination background 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange" 
        :current-page="current_page" :page-sizes="[10,20,30, 50]" 
        :page-size="listQuery.limit" layout="total, sizes, prev, pager, next" 
        :total="total"  
      >
      </el-pagination>
      </div>
    </div>
    <el-dialog title="提交申请" :visible.sync="dialogApplyVisible" >
      <el-form :rules="rules" ref="applyForm" :model="apply_temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="客户公司" >
          <span> {{this.current_company}}</span>
        </el-form-item>
        <el-form-item label="候选人" >
           <span> {{this.current_candidate}}</span>
        </el-form-item>
        <el-form-item label="费用类型" >
           <el-select class="filter-item" v-model="apply_temp.fee_type" placeholder="请选择" style="width:180px">
            <el-option v-for="item in fee_type_options" :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票类型" >
           <el-select class="filter-item" v-model="apply_temp.invoice_type" placeholder="请选择" style="width:180px">
            <el-option v-for="item in invoice_type_options" :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票金额" >
           <el-input size="small" v-model="apply_temp.invoice_amount" style="width: 480px;"></el-input>
        </el-form-item>
        <el-form-item label="发票内容" >
           <el-input size="small" v-model="apply_temp.content" style="width: 480px;"></el-input>
        </el-form-item>
        <el-form-item label="人事">
           <el-input size="small" v-model="apply_temp.hr" style="width: 480px;"></el-input>
        </el-form-item>
        <el-form-item label="人事邮箱" >
           <el-input size="small" v-model="apply_temp.hr_email" style="width: 480px;"></el-input>
        </el-form-item>
        <el-form-item label="邮寄地址" >
           <el-input size="small" v-model="apply_temp.ems_addr" style="width: 480px;"></el-input>
        </el-form-item>
        <el-form-item label="邮寄联系方式" >
           <el-input size="small" v-model="apply_temp.ems_contact_info" style="width: 480px;"></el-input>
        </el-form-item>
        <el-form-item label="审核人" >
           <el-select class="filter-item"
              v-model="apply_temp.current_op_id"
              filterable
              placeholder="请选择">
            <el-option
              v-for="item in allUserOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" >
          <el-input type="textarea" :rows="4" size="small" v-model="apply_temp.remark" style="width: 280px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogApplyVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="applyData()">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="撤回申请" :visible.sync="dialogBackVisible" >
      <el-form  :rules="back_rules" ref="backForm" :model="back_temp" label-position="left" label-width="120px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="客户公司" >
          <span> {{this.current_company}}</span>
        </el-form-item>
        <el-form-item label="候选人" >
           <span> {{this.current_candidate}}</span>
        </el-form-item>
        <el-form-item label="撤回备注" prop="remark" >
          <el-input type="textarea" :rows="4" size="small" v-model="back_temp.remark" style="width: 280px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBackVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="back()">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="审批" :visible.sync="dialogCheckVisible" append-to-body>
      <el-form :rules="check_rules" ref="checkForm" :model="check_temp" label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="客户公司" >
          <span> {{this.current_company}}</span>
        </el-form-item>
        <el-form-item label="候选人" >
           <span> {{this.current_candidate}}</span>
        </el-form-item>
        <el-form-item label="是否同意" required error="必须选择是否同意" prop="status">
          <el-radio v-model="check_temp.status" label="approved">同意</el-radio>
          <el-radio v-model="check_temp.status" label="no_pass">拒绝</el-radio>
        </el-form-item>
        <el-form-item label="财务" v-show="check_temp.status==='approved'">
           <el-select class="filter-item"
              v-model="check_temp.current_op_id"
              filterable
              placeholder="请选择">
            <el-option
              v-for="item in allUserOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" >
          <el-input type="textarea" v-model="check_temp.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCheckVisible = false">取 消</el-button>
        <el-button type="primary" @click="check()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="开票" :visible.sync="dialogBillVisible" append-to-body>
      <el-form :rules="bill_rules" ref="billForm" :model="bill_temp" label-position="left" label-width="120px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="客户公司" >
          <span> {{this.current_company}}</span>
        </el-form-item>
        <el-form-item label="候选人" >
           <span> {{this.current_candidate}}</span>
        </el-form-item>
        <el-form-item label="发票附件" >
          <el-upload
              class="upload-demo"
              action="/api/upload/invoice"
              :data="upload_temp"
              :headers="headers"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :before-remove="beforeRemove"
              :on-success="uploadSuccess"
              :limit="1"
              :on-exceed="handleExceed"
              list-type="picture-card"
              :file-list="fileList">
              <i class="el-icon-plus"></i>
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload> 
            <el-dialog :visible.sync="dialogImageVisible" append-to-body>
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
        </el-form-item>
        <el-form-item label="快递厂家及单号" >
           <el-input size="small" v-model="bill_temp.ems_no" style="width: 420px;"></el-input>
        </el-form-item>
        <el-form-item label="备注" >
          <el-input type="textarea" v-model="bill_temp.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBillVisible = false">取 消</el-button>
        <el-button type="primary" @click="bill()">确 定</el-button>
      </div>
    </el-dialog>



    <el-dialog title="打回" :visible.sync="dialogRepulseVisible" append-to-body>
      <el-form :rules="repulse_rules" ref="repulseForm" :model="repulse_temp" label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="客户公司" >
          <span> {{this.current_company}}</span>
        </el-form-item>
        <el-form-item label="候选人" >
           <span> {{this.current_candidate}}</span>
        </el-form-item>
        <el-form-item label="打回理由" prop="remark">
          <el-input type="textarea" v-model="repulse_temp.remark" style="width: 260px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRepulseVisible = false">取 消</el-button>
        <el-button type="primary" @click="repulse">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="作废" :visible.sync="dialogCancelVisible" append-to-body>
      <el-form :rules="cancle_rules" ref="cancelForm" :model="cancel_temp" label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="客户公司" >
          <span> {{this.current_company}}</span>
        </el-form-item>
        <el-form-item label="候选人" >
           <span> {{this.current_candidate}}</span>
        </el-form-item>
        <el-form-item label="作废理由" prop="remark">
          <el-input type="textarea" v-model="cancel_temp.remark" style="width: 260px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCancelVisible = false">取 消</el-button>
        <el-button type="primary" @click="discard">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="回款分配" :visible.sync="dialogAllocVisible" append-to-body>
      <el-form ref="allocForm" :rules="alloc_rules" :model="alloc_temp" label-position="left" label-width="100px" style='width: 650px; margin-left:20px;'>
        <el-form-item label="客户公司" >
          <span> {{this.current_company}}</span>
        </el-form-item>
        <el-form-item label="候选人" >
           <span> {{this.current_candidate}}</span>
        </el-form-item>
        <el-form-item label="发票金额" >
          <span>{{alloc_temp.invoice_amount}} RMB</span>
        </el-form-item>
        <div v-for="(item,index) in alloc_temp.invoice_cash_items" :key="index">
          <CashItem 
            :id="index"
            :item="item" 
            :invoice_amount="alloc_temp.invoice_amount" 
            :userOptions="allUserOptions" 
            @setCashItem="setAllocCashItem">
          </CashItem>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAllocVisible = false">取 消</el-button>
        <el-button type="primary" @click="alloc">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="退款" :visible.sync="dialogRefundVisible" append-to-body>
      <el-form ref="refundForm" :rules="refund_rules" :model="refund_temp" label-position="left" label-width="100px" style='width: 650px; margin-left:20px;'>
        <el-form-item label="客户公司" >
          <span> {{this.current_company}}</span>
        </el-form-item>
        <el-form-item label="候选人" >
           <span> {{this.current_candidate}}</span>
        </el-form-item>
        <el-form-item label="退款金额" prop='refund_amount'>
           <el-input size="small" v-model="refund_temp.refund_amount" style="width: 260px;">
             <template slot="append"><span>RMB</span></template>
           </el-input>
        </el-form-item>
        <div v-for="(item,index) in refund_temp.invoice_cash_items" :key="index">
          <CashItem 
            :id="index"
            :item="item" 
            :invoice_amount="refund_temp.refund_amount"
            :userOptions="allUserOptions" 
            @setCashItem="setRefundCashItem">
          </CashItem>
        </div>
        <el-form-item label="退款理由" prop="remark">
          <el-input type="textarea" v-model="refund_temp.remark" style="width: 260px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRefundVisible = false">取 消</el-button>
        <el-button type="primary" @click="refund">确 定</el-button>
      </div>
    </el-dialog>
    <PaymentNoticePrint :data="print_temp" :visible="dialogPrintVisible" @closeDialog="handleClosePrintDialog"> </PaymentNoticePrint>

    <el-tooltip placement="top" content="tooltip">
      <back-to-top transitionName="fade" :customStyle="myBackToTopStyle" :visibilityHeight="300" :backPosition="50"></back-to-top>
    </el-tooltip>
  </div>
</template>

<script>
import API from '@/utils/backend_api'
import Static_Data from '@/data/index'
import BackToTop from '@/components/BackToTop'
import CashItem from './components/cashItem'
import PaymentNoticePrint from './components/paymentNoticePrint'
import { getToken } from '@/utils/auth'

export default {
  name: 'invoice',
  components: { BackToTop, CashItem, PaymentNoticePrint },
  data() {
    return {
      current_user_id: this.$store.getters.userId,
      current_user_roles: this.$store.getters.roles,
      allUserOptions: this.$store.getters.usersList.map(item => ({ value: item.id, username: item.username, label: item.username + '(' + item.uid + ')' })),
      invoice_status_options: Static_Data.invoice_status,
      myBackToTopStyle: {
        right: '50px',
        bottom: '25px',
        width: '40px',
        height: '40px',
        'border-radius': '4px',
        'line-height': '45px', // 请保持与高度一致以垂直居中 Please keep consistent with height to center vertically
        background: '#e7eaf1'// 按钮的背景颜色 The background color of the button
      },
      total: 0,
      current_page: 1,
      listQuery: {
        page: 1,
        offset: 0,
        limit: 20,
        sort: '-CAST(create_date AS SIGNED)',
        create_id: '',
        company_name: '',
        candidate_name: '',
        invoice_status: ''
      },
      fee_type_options: Static_Data.fee_type,
      invoice_type_options: Static_Data.invoice_type,
      listLoading: true,
      list: [],
      multipleSelection: [],
      current_company: '',
      current_candidate: '',
      rules: {
      },
      check_rules: {},
      alloc_rules: {
        invoice_amount: [
          { validator: this.validatorNum, trigger: 'change' }
        ]
      },
      refund_rules: {
        refund_amount: [
          { validator: this.validatorNum, trigger: 'change' }
        ],
        remark: [
          { required: true, message: '必须填写理由', trigger: 'change' }
        ]

      },
      cancle_rules: {
        remark: [
          { required: true, message: '必须填写理由', trigger: 'change' }
        ]
      },
      repulse_rules: {
        remark: [
          { required: true, message: '必须填写理由', trigger: 'change' }
        ]
      },
      back_rules: {
        remark: [
          { required: true, message: '必须填写理由', trigger: 'change' }
        ]
      },
      bill_rules: {},
      apply_temp: {
        id: '',
        fee_type: '',
        invoice_type: '',
        invoice_amount: '',
        content: '',
        hr: '',
        hr_email: '',
        ems_addr: '',
        ems_contact_info: '',
        current_op_id: '',
        current_op_name: '',
        remark: ''
      },
      back_temp: {
        id: '',
        remark: ''
      },
      check_temp: {
        status: 'approved',
        current_op_id: '',
        current_op_name: '',
        remark: ''
      },
      bill_temp: {
        id: '',
        ems_no: '',
        invoice_attachment_url: '',
        remark: ''
      },
      print_temp: {
      },
      cancel_temp: {
        remark: ''
      },
      repulse_temp: {
        remark: ''
      },
      alloc_temp: {
        id: '',
        invoice_amount: '',
        remark: '',
        invoice_cash_items: [
        ]
      },
      refund_temp: {
        id: '',
        refund_amount: '',
        remark: '',
        invoice_cash_items: [
        ]
      },
      dialogRepulseVisible: false,
      dialogApplyVisible: false,
      dialogBackVisible: false,
      dialogCheckVisible: false,
      dialogBillVisible: false,
      dialogPrintVisible: false,
      dialogCancelVisible: false,
      dialogAllocVisible: false,
      dialogRefundVisible: false,
      upload_temp: {},
      fileList: [],
      headers: {
        Authorization: getToken(),
        smail: '*_~'
      },
      dialogImageVisible: false,
      dialogImageUrl: ''
    }
  },
  created() {
    this.getList()
    this.resetInvoiceCashItems()
  },
  computed: {
  },
  filters: {
  },
  methods: {
    getUsernameById(id) {
      let username = ''
      if (id && id !== '') {
        this.allUserOptions.map(item => {
          if (item.value === id) {
            username = item.username
          }
        })
      }
      return username
    },
    selfOperable(data) {
      return data.create_id && this.current_user_id === data.create_id
    },
    clientManagerOperable(data) {
      return data.business_roles && data.business_roles.some((item) => (item === 'client_manager'))
    },
    hasRoles(roles) {
      return this.current_user_roles.some(item => roles.indexOf(item) >= 0)
    },
    checkOperable(status, action) {
      if (status && action) {
        let action_group = []
        Static_Data.invoice_status.map(item => {
          if (item.key === status) {
            action_group = item.actions
          }
        })
        if (action_group.indexOf(action) < 0) {
          return false
        }
        return true
      } else {
        return false
      }
    },
    handleClosePrintDialog() {
      this.dialogPrintVisible = false
      this.print_temp = {}
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handleExceed(files, fileList) {
      this.$message.warning('当前限制选择 1 个文件，请先删除文件')
    },
    beforeRemove(file, fileList) {
      return this.$confirm('确定移除 ${ file.name }?')
    },
    uploadSuccess(response, file, fileList) {
      console.log(response.imgDataUrl)
      this.bill_temp.invoice_attachment_url = response.imgDataUrl
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    beforeUpload(file) {
    },
    setAllocCashItem(val) {
      this.alloc_temp.invoice_cash_items[val.id] = val.data
    },
    setRefundCashItem(val) {
      this.refund_temp.invoice_cash_items[val.id] = val.data
    },
    validatorNum(rule, value, callback) {
      const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
      if (reg.test(value) === false) {
        callback(new Error('只能输入数字,保留两位小数'))
      } else {
        callback()
      }
    },
    validatorProportionNum(rule, value, callback) {
      const reg = /^(?!00)(?:[0-9]{1,2}|100)$/
      if (reg.test(value) === false) {
        callback(new Error('请输入0-100的整数'))
      } else {
        callback()
      }
    },
    resetInvoiceCashItems() {
      this.alloc_temp.invoice_cash_items = []
      Static_Data.project_role.map(item => {
        this.alloc_temp.invoice_cash_items.push({
          project_role: item.key,
          project_role_name: item.display_name,
          cash_proportion: item.proportion,
          cash_amount: '0'
        })
      })
    },
    handleApply(data) {
      this.apply_temp.id = data.id
      this.apply_temp.fee_type = data.fee_type
      this.apply_temp.invoice_type = data.invoice_type
      this.apply_temp.invoice_amount = data.invoice_amount
      this.apply_temp.content = data.content
      if (data.project && data.project.client_manager) {
        this.apply_temp.current_op_id = data.project.client_manager
      }
      if (data.hr) {
        this.apply_temp.hr = data.hr
      }
      if (data.hr_email) {
        this.apply_temp.hr_email = data.hr_email
      }
      if (data.ems_addr) {
        this.apply_temp.ems_addr = data.ems_addr
      }
      if (data.ems_contact_info) {
        this.apply_temp.ems_contact_info = data.ems_contact_info
      }
      // if (data.current_op_id) {
      //   this.apply_temp.current_op_id = data.current_op_id
      // }
      if (data.remark) {
        this.apply_temp.remark = data.remark
      }
      this.dialogApplyVisible = true
    },
    handleRepulse(data) {
      this.repulse_temp.id = data.id
      this.repulse_temp.remark = ''
      this.dialogRepulseVisible = true
      this.$nextTick(() => {
        this.$refs['repulseForm'].clearValidate()
      })
    },
    handleBack(data) {
      this.back_temp.id = data.id
      this.back_temp.remark = ''
      this.dialogBackVisible = true
      this.$nextTick(() => {
        this.$refs['backForm'].clearValidate()
      })
    },
    handleCheck(data) {
      this.check_temp.id = data.id
      this.dialogCheckVisible = true
      if (data.status && data.status === 'no_pass') {
        this.check_temp.status = data.status
        if (data.remark) {
          this.check_temp.remark = data.remark
        }
      }
      this.$nextTick(() => {
        this.$refs['checkForm'].clearValidate()
      })
    },
    handleBill(data) {
      this.bill_temp.id = data.id
      this.dialogBillVisible = true
    },
    handleAlloc(data) {
      this.alloc_temp.id = data.id
      this.alloc_temp.invoice_amount = data.invoice_amount
      this.resetInvoiceCashItems()
      this.dialogAllocVisible = true
      this.$nextTick(() => {
        this.$refs['allocForm'].clearValidate()
      })
    },
    handlePrint(data) {
      this.print_temp = data
      this.dialogPrintVisible = true
    },
    handleCancel(data) {
      this.cancel_temp.id = data.id
      this.cancel_temp.remark = ''
      this.dialogCancelVisible = true
      this.$nextTick(() => {
        this.$refs['cancelForm'].clearValidate()
      })
    },
    handleRefund(data) {
      this.refund_temp.id = data.id
      this.refund_temp.refund_amount = data.invoice_amount
      API.invoice.all_cash({ invoice_id: data.id, cash_type: '0' }).then(response => {
        if (response.data) {
          this.refund_temp.invoice_cash_items = response.data
          this.dialogRefundVisible = true
          this.$nextTick(() => {
            this.$refs['refundForm'].clearValidate()
          })
        }
      })
    },
    applyData() {
      if (this.apply_temp.current_op_id) {
        this.allUserOptions.map(item => {
          if (item.value === this.apply_temp.current_op_id) {
            this.apply_temp.current_op_name = item.username
          }
        })
      }
      API.invoice.applyData(this.apply_temp.id, this.apply_temp).then(response => {
        for (const v of this.list) {
          if (v.id === this.apply_temp.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, response.data)
            break
          }
        }
        this.resetTemp()
        this.$message({
          type: 'success',
          message: '提交成功!'
        })
        this.dialogApplyVisible = false
      })
    },
    back() {
      this.$refs['backForm'].validate((valid) => {
        if (valid) {
          API.invoice.back(this.back_temp.id, this.back_temp).then(response => {
            for (const v of this.list) {
              if (v.id === this.back_temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, response.data)
                break
              }
            }
            this.resetTemp()
            this.$message({
              type: 'success',
              message: '撤回成功!'
            })
            this.dialogBackVisible = false
          })
        }
      })
    },
    check() {
      this.$refs['checkForm'].validate((valid) => {
        if (valid) {
          if (this.check_temp.status === 'approved' && this.check_temp.current_op_id) {
            this.allUserOptions.map(item => {
              if (item.value === this.check_temp.current_op_id) {
                this.check_temp.current_op_name = item.username
              }
            })
          }
          API.invoice.check(this.check_temp.id, this.check_temp.status, this.check_temp).then(response => {
            for (const v of this.list) {
              if (v.id === this.check_temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, response.data)
                break
              }
            }
            this.resetTemp()
            this.$message({
              type: 'success',
              message: '成功!'
            })
            this.dialogCheckVisible = false
          })
        }
      })
    },
    bill() {
      API.invoice.bill(this.bill_temp.id, this.bill_temp).then(response => {
        for (const v of this.list) {
          if (v.id === this.bill_temp.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, response.data)
            break
          }
        }
        this.resetTemp()
        this.$message({
          type: 'success',
          message: '成功!'
        })
        this.dialogBillVisible = false
      })
    },
    alloc() {
      this.$refs['allocForm'].validate((valid) => {
        if (valid) {
          console.log(this.alloc_temp)
          API.invoice.alloc(this.alloc_temp.id, {
            remark: '',
            invoice_cash_items: JSON.stringify(this.alloc_temp.invoice_cash_items || [])
          }).then(response => {
            for (const v of this.list) {
              if (v.id === this.alloc_temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, response.data)
                break
              }
            }
            this.resetTemp()
            this.$message({
              type: 'success',
              message: '回款分配成功!'
            })
            this.dialogAllocVisible = false
          })
        }
      })
    },
    repulse() {
      this.$refs['repulseForm'].validate((valid) => {
        if (valid) {
          API.invoice.back_to_check(this.repulse_temp.id, {
            remark: this.repulse_temp.remark
          }).then(response => {
            for (const v of this.list) {
              if (v.id === this.repulse_temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, response.data)
                break
              }
            }
            this.resetTemp()
            this.$message({
              type: 'success',
              message: '成功!'
            })
            this.dialogRepulseVisible = false
          })
        }
      })
    },
    discard() {
      this.$refs['cancelForm'].validate((valid) => {
        if (valid) {
          API.invoice.cancel(this.cancel_temp.id, {
            remark: this.cancel_temp.remark
          }).then(response => {
            for (const v of this.list) {
              if (v.id === this.cancel_temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, response.data)
                break
              }
            }
            this.resetTemp()
            this.$message({
              type: 'success',
              message: '成功!'
            })
            this.dialogCancelVisible = false
          })
        }
      })
    },
    print() {
    },
    refund() {
      this.$refs['refundForm'].validate((valid) => {
        if (valid) {
          console.log(this.refund_temp)
          API.invoice.refund(this.refund_temp.id, {
            refund_amount: this.refund_temp.refund_amount,
            remark: this.refund_temp.remark,
            invoice_cash_items: JSON.stringify(this.refund_temp.invoice_cash_items || [])
          }).then(response => {
            for (const v of this.list) {
              if (v.id === this.refund_temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, response.data)
                break
              }
            }
            this.resetTemp()
            this.$message({
              type: 'success',
              message: '退款成功!'
            })
            this.dialogRefundVisible = false
          })
        }
      })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleFilter() {
      this.getList()
    },
    handleCommand(val) {
      if (val.data && val.data.company) {
        this.current_company = val.data.company.company_name
      }
      if (val.data && val.data.candidate_name) {
        this.current_candidate = val.data.candidate_name
      }
      if (val.type && val.data && val.type === 'apply') {
        this.handleApply(val.data)
      }
      if (val.type && val.data && val.type === 'back') {
        this.handleBack(val.data)
      }
      if (val.type && val.data && val.type === 'repulse') {
        this.handleRepulse(val.data)
      }
      if (val.type && val.data && val.type === 'check') {
        this.handleCheck(val.data)
      }
      if (val.type && val.data && val.type === 'bill') {
        this.handleBill(val.data)
      }
      if (val.type && val.data && val.type === 'alloc') {
        this.handleAlloc(val.data)
      }
      if (val.type && val.data && val.type === 'print') {
        this.handlePrint(val.data)
      }
      if (val.type && val.data && val.type === 'cancel') {
        this.handleCancel(val.data)
      }
      if (val.type && val.data && val.type === 'refund') {
        this.handleRefund(val.data)
      }
    },
    clearOptions() {
      this.listQuery = {
        page: 1,
        offset: 0,
        limit: 20,
        sort: '-CAST(create_date AS SIGNED)',
        create_id: '',
        company_name: '',
        candidate_name: '',
        invoice_status: ''
      }
    },
    getList() {
      this.listLoading = true
      this.listQuery.departments = JSON.stringify(this.listQuery.departments_arr)
      API.invoice.all(this.listQuery).then(response => {
        this.list = response.data
        if (response.headers && response.headers['x-total-count']) {
          this.total = Number(response.headers['x-total-count'])
        }
        this.listLoading = false
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      if (val >= 1) {
        this.current_page = val
        this.listQuery.offset = (val - 1) * this.listQuery.limit
        this.getList()
      }
    },
    resetTemp() {
      this.apply_temp = {
        id: '',
        fee_type: '',
        invoice_type: '',
        invoice_amount: '',
        content: '',
        hr: '',
        hr_email: '',
        ems_addr: '',
        ems_contact_info: '',
        current_op_id: '',
        current_op_name: '',
        remark: ''
      }
      this.back_temp = {
        id: '',
        remark: ''
      }
      this.check_temp = {
        status: 'approved',
        current_op_id: '',
        current_op_name: '',
        remark: ''
      }
      this.bill_temp = {
        id: '',
        invoice_attachment_url: '',
        ems_no: '',
        remark: ''
      }
      this.print_temp = {
      }
      this.cancel_temp = {
        remark: ''
      }
      this.repulse_temp = {
        remark: ''
      }
      this.alloc_temp = {
        id: '',
        invoice_amount: ''
      }
      this.resetInvoiceCashItems()
      this.refund_temp = {
        id: '',
        refund_amount: '',
        remark: '',
        invoice_cash_items: [
        ]
      }
    },
    loadChildrenOptions(parent, callback/*, id */) {
      if (parent.children && parent.children.length > 0) {
        setTimeout(() => callback(null, parent.children), 100)
      } else {
        setTimeout(() => callback(null, []), 100)
      }
    }
  }
}
</script>

<style scoped>
  .form-table-border{
    margin: 1px 1px 1px 1px;
    border: 1px solid #ddd;
  }
  .search-container{
    display: block;
    border: 1px solid #ebebeb;
    margin: 2px 2px 2px 2px;
  }
  .search-option-row{
    display: block;
    margin: 6px 0px 6px 6px;
  } 
  .search-option-label{
    display: inline-block;
    width: 8%;
    text-align: right;
  }
  .search-option-col{
    display: inline-block;
    width:  15%;
  }
  .search-option-date-col{
    display: inline-block;
    width:  35%;
  }
  .search-button-row{
    display: block;
    margin: 2px 0px 2px 2px;
  }
  .search-button-label{
    display: inline-block;
    width: 8%;
    text-align: right;
  }
  .search-button-col{
    display: inline-block;
    width: 25%;
  }

  .table-header-row {
    display: block;
    border: 1px solid #ebebeb;
    margin: 2px 0px 2px 2px;
  }

  .table-header-button {
    display: inline-block;
    margin: 2px 0px 2px 2px;

  }

  .table-container{
    border: 1px solid #ebebeb;
    margin: 2px 2px 2px 2px;   
  }

  .table-container .small_tag{
    font-size: 12px;
  }

  .select-item {
    display: inline-block;
    vertical-align: middle;
    width: 200px;
  }

  .form-row {
    display: block;
  }

  .form-item {
    width: 48%
  }
  .form-item_part {
    width: 20%
  }
  .form-item-full {
    width: 100%
  }

  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>